package com.weai.service.impl;

import com.weai.config.DeepSeekConfig;
import com.weai.service.AIModelService;
import dev.langchain4j.model.chat.ChatLanguageModel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * AI模型服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AIModelServiceImpl implements AIModelService {

    /**
     * DeepSeek聊天模型
     */
    private final ChatLanguageModel chatModel;
    
    /**
     * DeepSeek配置
     */
    private final DeepSeekConfig deepSeekConfig;
    
    /**
     * 重试延迟（毫秒）
     */
    private static final long[] RETRY_DELAYS = {1000, 3000, 5000, 10000};
    
    @Override
    public String chat(String prompt) {
        // 使用默认重试次数
        return chat(prompt, deepSeekConfig.getMaxRetries());
    }
    
    @Override
    public String chat(String prompt, int maxRetries) {
        Exception lastException = null;
        
        for (int attempt = 0; attempt <= maxRetries; attempt++) {
            try {
//                log.info("提示词长度: {} 字符", prompt.length());
//                log.debug("模型提示词: \n{}", prompt);
                String response = chatModel.chat(prompt);
                log.info("模型响应长度: {} 字符", response.length());
                log.debug("原始模型响应内容: \n{}", response);
                
                // 清理模型响应
                response = cleanModelResponse(response);
                
                return response;
            } catch (Exception e) {
                lastException = e;
                log.warn("模型调用失败 (尝试 {}/{}): {}", attempt + 1, maxRetries + 1, e.getMessage());
                
                // 如果不是最后一次尝试，则等待后重试
                if (attempt < maxRetries) {
                    try {
                        // 使用指数退避策略
                        long delay = RETRY_DELAYS[Math.min(attempt, RETRY_DELAYS.length - 1)];
                        Thread.sleep(delay);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        throw new RuntimeException("线程中断", ie);
                    }
                }
            }
        }
        
        // 所有重试都失败
        if (lastException != null) {
            throw new RuntimeException("多次尝试调用模型失败", lastException);
        }
        
        return "模型调用失败";
    }
    
    @Override
    public String cleanModelResponse(String modelResponse) {
        if (modelResponse == null) {
            return "";
        }
        
        // 移除thinking标签
        if (modelResponse.contains("</think>")) {
            modelResponse = modelResponse.split("</think>")[1].trim();
            log.info("已清理<think>标签....");
        }
        
        // 清理代码块标记
        modelResponse = modelResponse.replace("```json", "")
                          .replace("```html", "")
                          .replace("```", "")
                          .trim();
        log.info("已清理json,html标签....");
        
        // 清理开头的换行符
        modelResponse = modelResponse.replaceAll("^(\\r\\n|\\n|\\r)+", "").trim();
        log.info("已清理开头的换行符....");

        return modelResponse;
    }
} 